/*
 *  Copyright (C) 2010 takaji
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * DefineTypeStep.java
 *
 * Created on Jan 24, 2010, 8:55:34 PM
 */
package dakside.hacc.modules.databridge.dataagent;

import dakside.hacc.core.config.Configuration;
import org.dakside.duck.dakwizard.AbstractWizardStep;
import org.dakside.duck.helpers.SwingHelper;
import dakside.hacc.modules.databridge.helpers.DataError;
import dakside.hacc.modules.databridge.helpers.TypeDefinition;
import dakside.hacc.modules.databridge.csvmodel.TransactionCSV;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author takaji
 */
public class DefineTypeStep extends AbstractWizardStep<ImportLoaderWizardModel> {

    /** Creates new form DefineTypeStep */
    public DefineTypeStep(ImportLoaderWizardModel model) {
        super(model, true);
        initComponents();
        SwingHelper.initCombobox(comboDataType,
                new Object[]{
                    new TransactionCSV()
                });
        txtFilePath.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                getWizardModel().setDataSourceValidated(false);
                getWizardModel().fireStateChanged();
            }

            public void removeUpdate(DocumentEvent e) {
                getWizardModel().setDataSourceValidated(false);
                getWizardModel().fireStateChanged();
            }

            public void changedUpdate(DocumentEvent e) {
                getWizardModel().setDataSourceValidated(false);
                getWizardModel().fireStateChanged();
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        choiceFile = new javax.swing.JRadioButton();
        choiceWebService = new javax.swing.JRadioButton();
        choiceDevice = new javax.swing.JRadioButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtFilePath = new javax.swing.JTextField();
        btnSelect = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        btnValidate = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        comboDataType = new javax.swing.JComboBox();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Data Source"));
        jPanel1.setName("jPanel1"); // NOI18N

        choiceFile.setSelected(true);
        choiceFile.setText("File/ Stream");
        choiceFile.setName("choiceFile"); // NOI18N

        choiceWebService.setText("Web Service");
        choiceWebService.setEnabled(false);
        choiceWebService.setName("choiceWebService"); // NOI18N

        choiceDevice.setText("Other device");
        choiceDevice.setEnabled(false);
        choiceDevice.setName("choiceDevice"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(choiceFile, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
                    .addComponent(choiceWebService, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
                    .addComponent(choiceDevice, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(choiceFile)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(choiceWebService)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(choiceDevice)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Location"));
        jPanel2.setName("jPanel2"); // NOI18N

        jLabel1.setText("File");
        jLabel1.setName("jLabel1"); // NOI18N

        txtFilePath.setName("txtFilePath"); // NOI18N

        btnSelect.setText("Select");
        btnSelect.setName("btnSelect"); // NOI18N
        btnSelect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(52, 52, 52)
                .addComponent(txtFilePath, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSelect, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSelect)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txtFilePath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Data Type"));
        jPanel3.setName("jPanel3"); // NOI18N

        jLabel2.setText("You have to validate file data to continue.");
        jLabel2.setName("jLabel2"); // NOI18N

        btnValidate.setText("Validate");
        btnValidate.setName("btnValidate"); // NOI18N
        btnValidate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnValidateActionPerformed(evt);
            }
        });

        jLabel3.setText("Data Type");
        jLabel3.setName("jLabel3"); // NOI18N

        comboDataType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboDataType.setName("comboDataType"); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(comboDataType, 0, 293, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnValidate, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(comboDataType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnValidate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectActionPerformed
        //show home folder by default, or previous selected file
        String start =
                (txtFilePath.getText().isEmpty())
                ? Configuration.getInstance().getHomeDirectory() : txtFilePath.getText();
        File f = SwingHelper.askOpen(start);
        if (f != null && f.exists() && f.isFile() && f.canRead()) {
            txtFilePath.setText(f.getAbsolutePath());
        }
    }//GEN-LAST:event_btnSelectActionPerformed

    private void btnValidateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnValidateActionPerformed
        //validate data
        File f = new File(txtFilePath.getText());
        if (f.exists() && f.isFile() && f.canRead()) {
            //can process
            getWizardModel().setDataSource(f);
            //set definition
            getWizardModel().setDataDefinition((TypeDefinition) comboDataType.getSelectedItem());
            //validate data
            final ValidatorWorker worker = new ValidatorWorker(f, getWizardModel().getDataDefinition());
            worker.addPropertyChangeListener(new PropertyChangeListener() {

                public void propertyChange(PropertyChangeEvent evt) {
                    if (evt.getPropertyName().equalsIgnoreCase("state")
                            && evt.getNewValue().toString().equals("DONE")) {
                        try {
                            DataError[] errors = worker.get();

                            if (errors.length == 0) {
                                //no errors
                                getWizardModel().setDataSourceValidated(true);
                                //notify
                                getWizardModel().fireStateChanged();
                            } else {
                                //TODO show list of error data here
//                                for (DataError dataError : errors) {
//                                    getWizardModel().getView().log(dataError.toString());
//                                }
                                SwingHelper.alert("Invalid data", "Invalid data file");
                            }
                        } catch (InterruptedException ex) {
                            Logger.getLogger(DefineTypeStep.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (ExecutionException ex) {
                            Logger.getLogger(DefineTypeStep.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            });

            worker.execute();
        }
    }//GEN-LAST:event_btnValidateActionPerformed

    @Override
    public boolean isCancellable() {
        return true;
    }

    @Override
    public boolean isFinishable() {
        return false;
    }

    @Override
    public boolean canGoNext() {
        return getWizardModel().isDataSourceValidated();
    }

    @Override
    public boolean canGoBack() {
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSelect;
    private javax.swing.JButton btnValidate;
    private javax.swing.JRadioButton choiceDevice;
    private javax.swing.JRadioButton choiceFile;
    private javax.swing.JRadioButton choiceWebService;
    private javax.swing.JComboBox comboDataType;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField txtFilePath;
    // End of variables declaration//GEN-END:variables
}
